<?php

namespace App\V3\V3_2_7\Controllers;


use App\Helper\Utils\TimeUtil;
use App\Rules\JsonArray;
use App\V3\V3_2_7\Models\CheckModel;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Services\CommonService;
use Illuminate\Support\Carbon;
use App\V3\V3_2_7\Services\BarterService;
use App\V3\V3_2_7\Services\SalesReturnsService;
use App\V3\V3_2_7\Services\SellService;
use App\V3\V3_2_7\Models\BarterModel;
use App\V3\V3_2_7\Models\BarterDriverModel;
use App\V3\V3_2_7\Models\BarterLogisticsInfoModel;
use App\V3\V3_2_7\Models\BarterOtherChargesModel;
use App\V3\V3_2_7\Models\SalesReturnModel;
use App\V3\V3_2_7\Services\OutInRepealService;
use App\V3\V3_2_7\Models\BarterGoodsDetailModel;
use App\V3\V3_2_7\Models\SalesReturnGoodsDetailModel;
use App\V3\V3_2_7\Models\BarterPayRecordModel;
use App\V3\V3_2_7\Services\IncomeExpensesService;


class BarterController extends BaseController
{
    /**
     * 添加换货单
     * change 在 2023/11/6 16:46 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'customer_name' => 'required',//客户姓名
            //'approver_id' =>'required|integer',//审批人
            'create_time' => 'required|date',//换货时间
            'source' => [
                Rule::In([0, 1, 2, 3, 4, 5, 6])
            ]//订单来源:0-未知 1-安卓 2-ios 3-pc 4-微信小程序 5-抖音小程序
        ], [
            /* 'approver_id.required' => '请选择审批人',
             'approver_id.integer' => '审批人`ID`为整数',*/
            'create_time.required' => '请选择创建时间',
            'create_time.date' => '创建时间不符合要求，请重新选择',
            'source.in' => '未知的订单来源'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $data['logTime'] = Carbon::now()->timestamp;
        //退货和换货主单
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $data['created_at'] = $data['logTime'];
        $data['barter_return_no'] = CommonService::getOrderNo(new BarterModel, 'barter_return_no', 'BR');//换货与退货共同关联编号
        //$data['barter_return_no'] = 'BR65881699425173377';//换货与退货共同关联编号
        if (empty($data['return_goods_info'])) return fail('', '退货商品必须选择');
        //创建退货
        $retrunArr = [];
        if (!empty($data['return_info'])) {
            $retrunArr = json_decode($data['return_info'], true);
            $res = SELF::validateData($retrunArr);
            if (!empty($res)) return fail('', $res);
        }
        $returnData = array_merge($data, $retrunArr);
        unset($returnData['spread_price']);
        unset($returnData['barter_info']);
        unset($returnData['barter_goods_info']);
        unset($returnData['barter_logistics_info']);
        $returnData['refund_date'] = strtotime($data['create_time']);
        $returnData['order_no'] = CommonService::getOrderNo(new SalesReturnModel, 'order_no', 'R');//订单号
        $retResult = BarterService::addReturn($returnData, $this->isUseShelf(), $this->isShareShelfLocation());
        if (!empty($retResult['code'])) return fail('', $retResult['msg']);
        //创建换货
        $barterArr = [];
        if (!empty($data['barter_info'])) {
            $barterArr = json_decode($data['barter_info'], true);
            $res = SELF::validateData($barterArr);
            if (!empty($res)) return fail('', $res);
        }
        $barterData = array_merge($data, $barterArr);;
        unset($barterData['return_info']);
        unset($barterData['return_goods_info']);
        unset($barterData['return_logistics_info']);
        $barterData['barter_date'] = strtotime($data['create_time']);
        $barterData['order_no'] = CommonService::getOrderNo(new BarterModel, 'order_no', 'B');//订单号
        $barResult = BarterService::addBarter($barterData, $this->isUseShelf(), $this->isShareShelfLocation());

        return response()->json($barResult);
    }

    /**
     * 修改换货单
     * change 在 2023/11/7 16:46 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'customer_name' => 'required',//客户姓名
            //'approver_id' =>'required|integer',//审批人
            'create_time' => 'required|date',//换货时间
            'source' => [
                Rule::In([0, 1, 2, 3, 4, 5])
            ]//订单来源:0-未知 1-安卓 2-ios 3-pc 4-微信小程序 5-抖音小程序
        ], [
            /*'approver_id.required' => '请选择审批人',
            'approver_id.integer' => '审批人`ID`为整数',*/
            'create_time.required' => '请选择创建时间',
            'create_time.date' => '创建时间不符合要求，请重新选择',
            'source.in' => '未知的订单来源'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $data['logTime'] = Carbon::now()->timestamp;
        //退货和换货主单
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        //修改退货
        if (!empty($data['return_info'])) {
            $data['return_info'] = json_decode($data['return_info'], true);
            $res = SELF::validateData($data['return_info']);
            if (!empty($res)) return fail('', '退货信息错误提示：' . $res);
        }
        //修改换货
        if (!empty($data['barter_info'])) {
            $data['barter_info'] = json_decode($data['barter_info'], true);
            $res = SELF::validateData($data['barter_info']);
            if (!empty($res)) return fail('', '换货信息错误提示：' . $res);
        }
        $result = BarterService::editReturnBarter($data, $this->isUseShelf(), $this->isShareShelfLocation());
        return response()->json($result);
    }

    /**
     * 退换货单列表
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2023/11/9 16:20
     * @return \Illuminate\Http\JsonResponse
     */
    public function barterReturnList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer|min:1',//当前页
            'repeal_status' => [
                'required',
                Rule::In([0, 1])
            ],//撤销状态：0-未撤销 1-已撤销
            'search_type' => [
                'required',
                Rule::In([0, 1, 2, 3, 4, 5, 6, 7, 8])
            ],
            'status' => [
                'required',
                Rule::In([0, 1, 2, 3])
            ]
        ], [
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`仅能为数字',
            'pageSize.min' => '`页面大小`仅能为1',
            'currentPage.required' => '`当前页大小`缺失',
            'currentPage.integer' => '`当前页`仅能为数字',
            'currentPage.min' => '`当前页`仅能为1',
            'repeal_status.required' => '`撤销状态`缺失',
            'repeal_status.in' => '`撤销状态`不合法',
            'search_type.required' => '`搜索类型`缺失',
            'search_type.in' => '`搜索类型`不合法',
            'status.required' => '`状态`缺失',
            'status.in' => '`状态`不合法',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if ($this->getUserId() == $this->getMainUserId() || $this->isShareReturnBarter() == 1) {
            $userId['main_id'] = ['EQ' => $this->getMainUserId()];
        } else {
            $userId['user_id'] = ['EQ' => $this->getUserId()];
        }
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $info = BarterService::barterReturnList($userId, $data);
        return $this->success($info);
    }

    /**
     * 换货单详细
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2023/11/9 17:04
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required',//换货单主键id
        ], [
            'id.required' => '参数`换货单id`缺失'
        ]);

        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        return response()->json(BarterService::detail($request->id));
    }

    /**
     * 删除
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2023/11/10 17:05
     * @return \Illuminate\Http\JsonResponse
     */
    public function del(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required',//换货单主键
        ], [
            'id.required' => '参数`换货单id`缺失'
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $barterInfo = BarterModel::select(
            'id',
            'order_no',
            'barter_return_no'
        )->where([
            'id' => $data['id'],
            'main_id' => $this->getMainUserId()
        ])->first();
        if (!empty($barterInfo)) {
            BarterModel::where('id', $barterInfo['id'])->update(['delete_flag' => 1]);
            BarterGoodsDetailModel::where('barter_id', $barterInfo['id'])->update(['delete_flag' => 1]);
            SalesReturnModel::where('barter_return_no', $barterInfo['barter_return_no'])->update(['delete_flag' => 1]);
        } else {
            return fail('', '没有找到，要删除的换货单！');
        }
        $logData = '换货号：' . $barterInfo['order_no'] . '已删除！';
        $this->log('删除换货单', $barterInfo, $logData);
        return $this->success();
    }

    /**
     * 收款
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2023/11/15 15:32
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMoney(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'barter_id' => 'required|integer',//换货单主键
            'money' => 'required|numeric',//收款金额
            'collection_time' => 'required|date',//收款时间
            //'collection_account'=>'required|string',//收款账号
            'money_flag' => [
                'required',
                Rule::in([0, 1])
            ],//支付类型：0-收款 1-退款
        ], [
            'money.required' => '金额，不能为空！',
            'money.numeric' => '金额异常，金额例如：0.01',
            'money_flag.required' => '支付类型，不能为空',
            'money_flag.in' => '支付类型，参数值错误！'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $barterInfo = BarterModel::select(
            'a.id as barter_id',
            'b.id as return_id',
            'a.order_no',
            'a.money as barter_money',
            'b.money as return_money',
            'spread_price',
            'other_charges',
            'a.pay_status',
            'a.real_money',
            'barter_date',
            'a.created_at'
        )->from('barter as a')
            ->leftJoin(
                'sales_return as b',
                'b.barter_return_no',
                '=',
                'a.barter_return_no'
            )->where([
                'a.id' => $data['barter_id'],
                'a.main_id' => $this->getMainUserId(),
                'a.delete_flag' => 0,
                'a.repeal_status' => 0
            ])->first();//换货单信息
        if (strtotime($barterInfo['created_at']) > '1713506400') {//2024年4月19日 14点之前的订单不需要审核
            $checkInfo = CheckModel::where([
                'all_id' => $barterInfo['barter_id'],
                'type' => 4,
                'repeal_status' => 0
            ])->first();
            if (!empty($checkInfo)) {
                if (empty($checkInfo['eudit_status'])) {
                    return fail('', '退换货单在待审批中！');
                }
                if ($checkInfo['eudit_status'] == 2) {
                    return fail('', '退换货单未审批通过！');
                }
            }
        }
        if (empty($barterInfo)) {
            return fail('', '退换货单信息，没有找到！');
        }
        if (!empty($barterInfo['pay_status'])) {
            return fail('', '退换货单：' . $barterInfo['order_no'] . '，已支付！');
        }
        $recordInfo = BarterPayRecordModel::where([
            'barter_id' => $barterInfo['barter_id']
        ])->first();//已收款金额

        if (!empty($recordInfo)) {
            return fail('', '退换货单：' . $barterInfo['order_no'] . '的记录，已存在！');
        }
        $money = 0;
        $payType = 0;
        //开启事务
        DB::beginTransaction();
        try {
            if (empty($barterInfo['barter_money']) && !empty($barterInfo['return_money'])) {
                $money = $barterInfo['return_money'] + $barterInfo['other_charges'];

            } elseif (!empty($barterInfo['barter_money']) && empty($barterInfo['return_money'])) {
                $money = $barterInfo['barter_money'] + $barterInfo['other_charges'];
            } else {
                $money = $barterInfo['return_money'] - $barterInfo['barter_money'];
            }

            if (0 <= $money) {
                if (empty($data['money_flag'])) {
                    throw new Exception('退款类型错误！');
                }
                $logTit = '退款';
            } else {
                if (!empty($data['money_flag'])) {
                    throw new Exception('收款类型错误！');
                }
                $logTit = '收款';
            }

            if (!empty($barterInfo['other_charges'])) {
                $money = abs($money + $barterInfo['other_charges']);
            } else {
                $money = abs($money);
            }

            if ($money != $data['money']) {
                throw new Exception('应付金额有误，应付金额为：' . $money . '元！');
            }
            //全部收款
            $updData = [
                'pay_status' => 2,
                'real_money' => $money
            ];
            BarterModel::where([
                'id' => $barterInfo['barter_id']
            ])->update($updData);
            SalesReturnModel::where([
                'id' => $barterInfo['return_id']
            ])->update($updData);
            //收款记录
            $data['collection_time'] = strtotime($data['collection_time']);
            $data['created_at'] = time();
            $data['main_id'] = $this->getMainUserId();
            unset($data['money']);
            $data['expend'] = $money;
            $data['pay_type'] = !empty($data['pay_type']) ? $data['pay_type'] : 0;
            BarterPayRecordModel::insert($data);
            $logData = '退换货号：' . $barterInfo['order_no'] . $logTit . '金额为：' . $money . '元';
            $this->log('退换货' . $logTit, $data, $logData);
            //账单记录
            IncomeExpensesService::tally(
                2,
                $barterInfo['order_no'],
                $money,
                $this->getMainUserId(),
                $barterInfo['barter_date'],
                $data['money_flag'],
                $this->getUserId()
            );
            DB::commit();//提交事务
            return $this->success();
        } catch (Exception $e) {
            DB::rollBack();//事务回滚
            Log::debug('销售单收款' . var_export($e->getMessage(), true));
            //异常响应
            return $this->fail('', $e->getMessage());
        }
    }

    /**
     * 重新下单
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2023/11/10 15:33
     * @return \Illuminate\Http\JsonResponse
     */
    public function addAgain(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//换货主键
        ], [
            'id.required' => '参数`换货主键id`缺失'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $data['logTime'] = time();
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $data['batch_title'] = $this->batchTitle();

        return response()->json(BarterService::addAgain($data));
    }

    /**
     * 撤销
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function repeal(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//换货主键
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['logTime'] = time();
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $res = BarterService::repeal($data);
        return response()->json($res);
    }

    /**
     * 换货单收款记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function payHistory(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//退货换单主键
        ], [
            'id.required' => '退货换单，主键缺失！',//退货换单主键
            'id.integer' => '退货换单，主键为正整数！',//退货换单主键
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        return $this->success(BarterService::payHistory($request->id));
    }

    /**
     * 销售单已有快递单号列表
     * @param Request $request
     * 2022/8/22 20:20
     * Author: Sun Wu
     * @return \Illuminate\Http\JsonResponse
     */
    public function sellExpressInfo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'pageSize' => 'required|integer',//页面大小
            'currentPage' => 'required|integer',//当前页
        ], [
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`仅能为数字',
            'pageSize.min' => '`页面大小`仅能为0',
            'currentPage.required' => '`当前页大小`缺失',
            'currentPage.integer' => '`当前页`仅能为数字',
            'currentPage.min' => '`当前页`仅能为0',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        //是否共享
        $condition = [];
        if (!$this->isShareExpress()) {
            if ($this->getUserTpye()) {
                $condition['user_id'] = ['EQ' => $this->getUserId()];
            } else {
                $condition['main_id'] = ['EQ' => $this->getMainUserId()];
            }
        } else {
            $condition['main_id'] = ['EQ' => $this->getMainUserId()];
        }

        $keyword = isset($data['code']) ? $data['code'] : '';

        $model = SellModel::select('logistics_order_no', 'logistics_company')->where($condition)
            ->where('repeal_status', 0)
            ->where('delete_flag', 0)
            ->where('logistics_order_no', '!=', '')
            ->where('logistics_order_no', 'LIKE', '%' . $keyword . '%')
            ->orderBy('id', 'desc')
            ->paginate($data['pageSize'], ['*'], '', $data['currentPage'])->toArray();

        return $this->success($model);
    }

    /**
     * 其他费用添加
     * change 在 2023/11/9 14:41 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addOtherCharges(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'barter_id' => 'required|integer',//换货单主键id
            'money' => 'required|regex:/^\d+(\.\d{1,2})?$/',//其他费用
            'other_type_name' => 'required',//其他费用类型名称
        ], [
            'barter_id.required' => '换货单主键`id`必要参数',
            'barter_id.integer' => '换货单主键`id`为正整数',
            'money.required' => '费用金额，不能为空！',
            'money.regex' => '费用金额，格式不正确！如：0.00',
            'other_type_name.required' => '其他费用类型名称，不能为空！',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['created_at'] = time();
        //开启事务
        DB::beginTransaction();
        try {
            BarterOtherChargesModel::insert($data);
            $model = BarterModel::where('id', $data['barter_id'])->first();
            $model->other_charges = $model->other_charges + $data['money'];
            $model->save();
            $this->log('换货单-添加其他费用', $data, '换货号:' . $model['order_no'] . '添加其他费用为' . $data['money'] . '元');
            DB::commit();//提交事务
            return $this->success();
        } catch (Exception $e) {
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(), '添加其他费用');
        }
    }

    /**
     * 其他费用列表
     * change 在 2023/11/9 14:41 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function otherChargesList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'barter_id' => 'required|integer',//换货单主键id
        ], [
            'barter_id.required' => '换货单主键`id`必要参数',
            'barter_id.integer' => '换货单主键`id`为正整数',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $model = BarterOtherChargesModel::where('barter_id', $data['barter_id'])->get();
        return $this->success($model);
    }

    /**
     * 其他费用编辑
     * change 在 2023/11/9 14:41 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function otherChargesEdit(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//其他费用主键id
            'money' => 'required|regex:/^\d+(\.\d{1,2})?$/',//其他费用
            'other_type_name' => 'required',//其他费用类型名称
        ], [
            'id.required' => '其他费用主键`id`必要参数',
            'id.integer' => '其他费用主键`id`为正整数',
            'money.required' => '费用金额，不能为空！',
            'money.regex' => '费用金额，格式不正确！如：0.00',
            'other_type_name.required' => '其他费用类型名称，不能为空！',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        //开启事务
        DB::beginTransaction();
        try {
            $beforeModel = BarterOtherChargesModel::where('id', $data['id'])->first();
            BarterOtherChargesModel::where('id', $data['id'])->update($data);
            $beforeMoney = $beforeModel['money'];
            $final = $data['money'] - $beforeMoney;
            $model = BarterModel::where('id', $beforeModel['barter_id'])->first();
            $model->other_charges = $model->other_charges + $final;
            $model->save();
            $this->log('销售单-编辑其他费用', $data, '销售单号:' . $model['order_no'] . '修改其他费用为' . $data['money'] . '元');
            DB::commit();//提交事务
            return $this->success();
        } catch (Exception $e) {
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(), '添加其他费用');
        }
    }

    /**
     * 绑定司机(添加编辑)
     * change 在 2023/11/9 09:40 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bindDriver(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'barter_id' => 'required|integer',//换货单主键id
            'plate_number' => 'required',//车牌
            'name' => 'required',//司机姓名
            'phone' => 'required',//提货司机电话
        ], [
            'barter_id.required' => '换货单主键`id`必要参数',
            'barter_id.integer' => '换货单主键`id`为正整数',
            'plate_number.required' => '车牌，不能为空！',
            'name.required' => '司机姓名，不能为空！',
            'phone.required' => '提货司机电话，不能为空！',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['created_at'] = time();
        $orderNo = BarterModel::where('id', $data['barter_id'])->value('order_no') ?? '';

        DB::beginTransaction();
        try {
            $res = '换货单：' . $orderNo . ' 司机名：' . $data['name'] . '添加成功！';
            if (isset($data['driver_id'])) {
                $res = '换货单：' . $orderNo . ' 司机名：' . $data['name'] . '修改成功！';
                $driverId = $data['driver_id'];
                unset($data['driver_id']);
                BarterDriverModel::where('id', $driverId)->update($data);
            } else {
                BarterDriverModel::insert($data);
            }
            $this->log('换货单绑定司机', $res);
            DB::commit();
            return $this->success();
        } catch (\Exception $e) {
            DB::rollBack();
            return fail('', $e->getMessage());
        }

    }

    public function sellSerialList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'type_id' => 'required|integer',//其他费用主键id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();

        return $this->success(
            sellService::sellSerialList($data)
        );
    }

    /**
     * 换货单添加物流信息
     * @param Request $request
     */
    public function addBarterExpressNumber(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'barter_id' => 'required|integer',//换货单主键id
            'barter_logistics_info' => [
                'required',
                'json',
                new JsonArray([
                    'logistics_company' => 'required',//物流公司名称
                    'logistics_order_no' => 'required',//物流单号
                ])
            ]
        ], [
            'barter_id.required' => '换货单主键id,不能为空',
            'barter_id.integer' => '换货单主键id,只能为整数',
            'barter_logistics_info.required' => '物流信息,不能为空',
            'barter_logistics_info.json' => '物流信息数据格式为json',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['main_id'] = $this->getMainUserId();
        $orderNo = BarterModel::where([
            'id' => $data['barter_id'],
        ])->value('order_no');
        if (!empty($orderNo)) {
            if (!empty($data['barter_logistics_info'])) {//添加物流信息
                $logisticsData = [];
                $sellLogisticsInfo = json_decode($data['barter_logistics_info'], true);
                if (is_array($sellLogisticsInfo)) {
                    foreach ($sellLogisticsInfo as $sVal) {
                        if (!empty($sVal['logistics_company']) && empty($sVal['logistics_order_no'])) {
                            return fail('', '物流公司名称：' . $sVal['logistics_company'] . '物流号不能为空');
                        }
                        if (empty($sVal['logistics_company']) && !empty($sVal['logistics_order_no'])) {
                            return fail('', '物流号：' . $sVal['logistics_order_no'] . '物流公司名称不能为空');
                        }
                        $logisticsData[] = [
                            'user_id' => $this->getUserId(),
                            'main_id' => $this->getMainUserId(),
                            'barter_id' => $data['barter_id'],
                            'logistics_company' => $sVal['logistics_company'],
                            'logistics_order_no' => $sVal['logistics_order_no'],
                            'created_at' => Carbon::now()->timestamp
                        ];
                    }
                    if (!empty($logisticsData)) {
                        BarterLogisticsInfoModel::insert($logisticsData);
                    }
                } else {
                    return fail('', '物流信息异常');
                }
            }
        } else {
            return fail('', '换货单信息，没有找到！');
        }
        $logData = '换货单号 ：' . $orderNo . '的物流信息，添加成功！';
        $this->log('换货单添加物流信息', $data, $logData);
        return $this->success();
    }

    /**
     * 新建换货单时填充销售单信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|unknown
     */
    public function getSellGoodsInfo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'sell_id' => 'required|integer',//销售单主键id
        ], [
            'sell_id.required' => '销售单主键id,不能为空',
            'sell_id.integer' => '销售单主键id,只能为整数',

        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data ['main_id'] = $this->getMainUserId();
        return success(SellService::getSellGoodsInfo($data));
    }

    /**
     * 退换货出入库
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function barterOutOrIn(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//换货主键id
            'is_out_or_in' => [//出入库标示：1出，0入
                'required',
                Rule::in([1, 0])
            ]
        ], [
            'id.required' => '参数`换货单id`缺失',
            'is_out_or_in.required' => '参数`出入库标示`缺失',
            'is_out_or_in.in' => '参数`出入库标示`值是：0或1',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $data['logTime'] = Carbon::now()->timestamp;
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['batch_title'] = $this->batchTitle();
        if (!empty($data['is_out_or_in'])) {
            $result = BarterService::barterOut($data, $this->isUseShelf(), $this->batchTitle());
        } else {
            $result = BarterService::returnIn($data, $this->isUseShelf());
        }
        return response()->json($result);
    }


    static public function validateData($data)
    {
        //参数验证
        $validator = Validator::make($data, [
            'deliver_goods_type' => [
                Rule::In([1, 2, 3])
            ],//发货方式：1-自提 2-代发 3-送货
            'transport_type' => [
                Rule::In([1, 2, 3, 4])
            ],//运输方式：1-空运 2-海运 3-铁路 4-公路
            'source' => [
                Rule::In([0, 1, 2, 3, 4, 5])
            ]//订单来源:0-未知 1-安卓 2-ios 3-pc 4-微信小程序 5-抖音小程序
        ], [
            'deliver_goods_type.in' => '您选择了未知的发货方式',
            'transport_type.in' => '您选择了未知的运输方式',
            'source.in' => '未知的订单来源'

        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $info;
        }
    }

    /**
     *换货司机列表
     * Author: zlf
     * Created at 2024/1/31 10:50
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function barterDriverList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'barter_id' => 'required|integer',//销售单主键id
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer|min:1',//当前页
        ], [
            'barter_id.required' => '换货单主键id,不能为空',
            'barter_id.integer' => '换货单主键id,只能为整数',
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`仅能为数字',
            'pageSize.min' => '`页面大小`仅能为1',
            'currentPage.required' => '`当前页大小`缺失',
            'currentPage.integer' => '`当前页`仅能为数字',
            'currentPage.min' => '`当前页`仅能为1',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $data['main_id'] = $this->getMainUserId();
        return $this->success(BarterService::barterDriverList($data));
    }

    /**
     *删除换货司机
     * Author: zlf
     * Created at 2024/1/31 11:04
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delBarterDriver(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'barter_id' => 'required|integer',//换货单主键id
            'driver_id' => 'required|integer',//司机表主键id
        ], [
            'barter_id.required' => '换货单主键id,不能为空',
            'barter_id.integer' => '换货单主键id,只能为整数',
            'driver_id.required' => '司机表主键id,不能为空',
            'driver_id.integer' => '司机表主键id,只能为整数',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $data['main_id'] = $this->getMainUserId();
        return $this->success(BarterService::delBarterDriver($data));
    }

    /**
     * 只修改换货单（客户发货单）
     * change 在 2023/11/7 16:46 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function editSwapOrder(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//销售单主键id
            'transport_type' => [
                Rule::In([1, 2, 3, 4])
            ],//运输方式：1-空运 2-海运 3-铁路 4-公路
            'deliver_time' => 'required|date',//换货时间
        ], [
            'barter_id.required' => '换货单主键id,不能为空',
            'barter_id.integer' => '换货单主键id,只能为整数',
            'transport_type.in' => '您选择了未知的运输方式',
            'deliver_time.required' => '请选择创建时间',
            'deliver_time.date' => '创建时间不符合要求，请重新选择',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $data['main_id'] = $this->getMainUserId();
        $result = BarterService::editSwapOrder($data);
        return response()->json($result);
    }
}
